<?php
namespace app\api\controller\login;

use app\api\controller\Member;
use app\common\model\CourseAttendanceModel;
use app\common\model\CourseModel;
use app\common\model\UserModel;
use app\common\model\UserTimesModel;
use think\db;
use think\exception\DbException;

class Student extends Member
{
    /**
     * 获取学生的常规课程
     */
    public function getCourseNormal(){
        $user = $this->getMember();
        $page = $this->request->get('page', 1);
        $cate_id = $this->request->get('cate_id');
        $keyword = $this->request->get('keyword');
        $order = ['sort'=>'asc','id'=>'desc'];
        $course = CourseModel::where('status',1)
            ->where('type',1)
            ->where('school_id',$user['school_id'])
            ->where('grade_id='.$user['grade_id'].' or grade_id is null')
            ->where('class_id='.$user['class_id'].' or class_id is null')
            ->where(function ($db) use ($cate_id,$keyword) {
                if (!empty($cate_id)) {
                    $db->where('cate_id', $cate_id);
                }
                if (!empty($keyword)) {
                    $db->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->order($order)
            ->page($page,20)
            ->select()
            ->toArray();
        $this->success('获取所有常规课程成功！',$course,200);
    }

    /**
     * 获取学生的兴趣课程
     */
    public function getCourseInterest(){
        $user = $this->getMember();
        $page = $this->request->get('page', 1);
        $cate_id = $this->request->get('cate_id');
        $keyword = $this->request->get('keyword');
        $order = ['sort'=>'asc','id'=>'desc'];
        $course_ids = UserTimesModel::where('user_id',$user['id'])
            ->field('group_concat(course_id) as course_ids')->find()['course_ids'];
        $course = CourseModel::where('status',1)
            ->where('type',2)
            ->where('id','in',$course_ids)
            ->where(function ($db) use ($cate_id,$keyword) {
                if (!empty($cate_id)) {
                    $db->where('cate_id', $cate_id);
                }
                if (!empty($keyword)) {
                    $db->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->order($order)
            ->page($page,20)
            ->select()
            ->toArray();
        $this->success('获取所有兴趣课程成功！',$course,200);
    }

    /**
     * 获取学生的已学习课程
     */
    public function getCourseAttendance(){
        $user = $this->getMember();
        $page = $this->request->get('page', 1);
        $cate_id = $this->request->get('cate_id');
        $keyword = $this->request->get('keyword');
        $order = ['sort'=>'asc','id'=>'desc'];
        $course_ids = CourseAttendanceModel::where('find_in_set('.$user['id'].',in_userids)')
            ->field('group_concat(course_id) as course_ids')->find()['course_ids'];
        $course = CourseModel::where('status',1)
            ->where('id','in',$course_ids)
            ->where(function ($db) use ($cate_id,$keyword) {
                if (!empty($cate_id)) {
                    $db->where('cate_id', $cate_id);
                }
                if (!empty($keyword)) {
                    $db->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->order($order)
            ->page($page,20)
            ->select()
            ->toArray();
        $this->success('获取所有已学习课程成功！',$course,200);
    }

    /**
     * 获取学生的学习时长与次数
     */
    public function getTimeCount(){
        $user = $this->getMember();
        $result['count'] = CourseAttendanceModel::where('find_in_set('.$user['id'].',in_userids)')->count();
        $result['time'] =  ceil(45*$result['count']/60);
        $this->success('获取学生的学习时长与次数成功！',$result,200);
    }

    /**
     * 学生选课
     */
    public function addUserTime(){
        $user = $this->getMember();
        $course_id = $this->request->post('course_id');
        $course = CourseModel::where('id',$course_id)->find();
        if(!empty($course['begin_choose_time'])&&time()<strtotime($course['begin_choose_time'])){
            $this->error('未到选课开始时间:'.$course['begin_choose_time'],'',400);
        }
        if(!empty($course['end_choose_time'])&&time()>strtotime($course['end_choose_time'])){
            $this->error('已超过选课结束时间:'.$course['end_choose_time'],'',400);
        }
        $teacher_id = $this->request->post('teacher_id');
        $time = $this->request->post('time');
        if($user['id']==0){
            $this->error('登录未成功，请删除小程序后重新授权','',400);
        }
        if(empty($user['realname'])){
            $this->error('真实姓名未填，请去个人中心修改信息','',400);
        }

        if(!empty($course['school_id']) && $course['school_id']!=$user['school_id']){
            $this->error('学生绑定学校不符','',400);
        }

        $old = UserTimesModel::where('user_id',$user['id'])
            ->where('course_id',$course_id)
            ->where('teacher_id',$teacher_id)
            ->find();
        if(!empty($old)){
            $this->error('已经选择过此课程了！','',400);
        }
        $old2 = UserTimesModel::where('user_id',$user['id'])->find();
        if(!empty($old2)){
            $this->error('已经选择过其它课程了！','',400);
        }
        $has_count = UserTimesModel::where('course_id',$course_id)->count();//已报名人数
        if($course['sign_total']<=$has_count){
            $this->error('该课程人数已满，不可报名！','',400);
        }
        if (!$this->getAddUserTimeLock($course_id)){
            $this->error('服务器拥挤，请重试','',400);
        }
        // 启动事务
        Db::startTrans();
        try{
            $user_time = UserTimesModel::create([
                'user_id'=>$user['id'],
                'course_id'=>$course_id,
                'teacher_id'=>$teacher_id,
                'time'=>$time,
                'create_time'=>date('Y-m-d H:i:s')
            ]);
            CourseModel::where('id',$course_id)->setInc('sign_count');
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $user_time = null;
        }

        $this->releaseLock($course_id);
        if(!empty($user_time)){
            $this->success('选课成功！',$user_time,200);
        }else{
            $this->error('选课失败,请刷新重试！','',400);
        }
    }

    /**
     * 班主任查看学生列表
     * @return void
     */
    public function getMyStudentList(){
        $user = $this->getMember();

        $student = [];
        if($user['grade_id'] > 0 && $user['class_id'] > 0){
            try {
                $student = (new UserModel)->alias('u')
                    ->join('edu_user_times t','t.user_id=u.id','LEFT')
                    ->join('edu_course c','t.course_id=c.id','INNER')
                    ->where('u.school_id', $user['school_id'])
                    ->where('u.grade_id', $user['grade_id'])
                    ->where('u.class_id', $user['class_id'])
                    ->where('u.role', 1)
                    ->field('u.id,u.realname, u.student_no, GROUP_CONCAT(DISTINCT c.name) as course_name')
                    ->group('u.id')
//                ->fetchSql(true)
                    ->select()
                ;
            } catch (\Exception $e) {
            }

        }

        $this->success('success',$student,200);
    }

    /**
     * 学籍号登录
     * @param string student_no 学籍号
     * @param string pwd 密码
     * @throws DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function studentNoLogin()
    {
        $student_no = trim($this->request->post('student_no'));
        $pwd = trim($this->request->post('pwd'));
        if(!empty($student_no) and !empty($pwd))
        {
            $pwd = md5($pwd);
            $stu = UserModel::where('student_no', $student_no)->where('pwd', $pwd)->find();
            if(!empty($stu)){
                $this->success('登录成功！',$stu,200);
            }
        }
        $this->error('登录失败,请重试！','',400);
    }

    /**
     * 学籍号绑定
     * @param string student_no 学籍号
     * @param string pwd 密码
     * @throws DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function studentNoBind()
    {
        $user = $this->getMember();
        $student_no = trim($this->request->post('student_no'));
        $pwd = trim($this->request->post('pwd'));
        if(!empty($student_no) and !empty($pwd))
        {
            $pwd = md5($pwd);
            $stu = UserModel::where('student_no', $student_no)->where('pwd', $pwd)->find();
            if(!empty($stu)){
                $stu->pid = $user->id;
                $stu->phone = $user->phone;
                $stu->save();
                $this->success('绑定成功！',$stu,200);
            }
        }
        $this->error('绑定失败,请重试！','',400);
    }

    /**
     * 获取已绑定的孩子列表
     * @throws DbException
     */
    public function getStudentBindList()
    {
        $user = $this->getMember();


//        $pid = input('?pid') ?
//            ((input('pid')=='undefined' OR input('pid')=='UNDEFINED') ? $user->id : input('pid'))
//            :
//            $user->id;

        // 家长
        if($user->pid === 0){
            $pid = $user->id;
        }else{
            $pid = $user->pid;
        }

        $stu = UserModel::where(function ($query) use ($pid){
            $query->where('u.pid', $pid)->whereOr('u.id',$pid);
        })->alias('u')
            ->leftJoin('edu_school_class c','c.id=u.class_id')
            ->leftJoin('edu_school_grade g','g.id=u.grade_id')
            ->field('u.*,g.name AS grade_name,c.name AS class_name')
            ->where([
                ['u.role','=',1]
            ])
//            ->fetchSql()
            ->select();
        $this->success('获取成功！',$stu,200);
    }

    protected function getAddUserTimeLock($course_id){
        $LOCK_NAME = 'course'.$course_id;

        $lock = cache($LOCK_NAME);

        if(empty($lock)){
            cache($LOCK_NAME,1,300);
            return true;
        }

        return false;
    }

    protected function releaseLock($course_id){
        $LOCK_NAME = 'course'.$course_id;
        cache($LOCK_NAME,NULL);
    }
}